package JAVA并发;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangmin
 * @create 2022-03-16 15:42
 */
public class ThreadExample11_ReentrantLock {
    private int cnt=0;

    private Lock lock=new ReentrantLock();

    //进行加锁
    public synchronized void add(){
        lock.lock();
        cnt++;
        lock.unlock();
    }
    public int get(){
        return cnt;
    }

    public static void main(String[] args) throws InterruptedException {
        final int threadsize=1000;
        ThreadExample11_ReentrantLock e=new ThreadExample11_ReentrantLock();
        final CountDownLatch countDownLatch=new CountDownLatch(threadsize);
        ExecutorService executorService= Executors.newCachedThreadPool();
        for (int i = 0; i < threadsize; i++) {
            executorService.execute(()->{
                e.add();
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(e.get());
    }
}
